package com.blogs.service;

import java.util.HashMap;
import java.util.Map;

import com.blogs.entity.AppConfig;
import com.blogs.tools.DBHandler;

import android.content.Context;
import android.database.Cursor;

public class FileService extends DBHandler{

    public FileService(Context context) {
    	super(context);
    }
    
    /**
     * 获取每条线程已经下载的文件长度
     * @param path
     * @return
     */
    public Map<Integer, Integer> getData(String path){
    	if(!rdb.isOpen())
    		rdb=getReadableDatabase();
        Cursor cursor =rdb.rawQuery("select threadid, downlength from "+AppConfig.DB_DownLoad_TB+" where downpath=?", new String[]{path});
        Map<Integer, Integer> data = new HashMap<Integer, Integer>();
        
        while(cursor.moveToNext()){
            data.put(cursor.getInt(0), cursor.getInt(1));
        }
        cursor.close();
        rdb.close();
        return data;
    }
    
    /**
     * 保存每条线程已经下载的文件长度
     * @param path
     * @param map
     */
    public void save(String path,  Map<Integer, Integer> map){//int threadid, int position
    	if(!wdb.isOpen())
    		wdb=getWritableDatabase();
        wdb.beginTransaction();
        
        try{
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            	wdb.execSQL("insert into "+AppConfig.DB_DownLoad_TB+"(downpath, threadid, downlength) values(?,?,?)",
                        new Object[]{path, entry.getKey(), entry.getValue()});
            }
            wdb.setTransactionSuccessful();
        }finally{
        	wdb.endTransaction();
        }
        wdb.close();
    }
    
    /**
     * 实时更新每条线程已经下载的文件长度
     * @param path
     * @param map
     */
    public void update(String path, Map<Integer, Integer> map){
    	if(!wdb.isOpen())
    		wdb=getWritableDatabase();
        wdb.beginTransaction();
        
        try{
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            	wdb.execSQL("update "+AppConfig.DB_DownLoad_TB+" set downlength=? where downpath=? and threadid=?",
                        new Object[]{entry.getValue(), path, entry.getKey()});
            }
            
            wdb.setTransactionSuccessful();
        }finally{
        	wdb.endTransaction();
        }
        wdb.close();
    }
    
    /**
     * 当文件下载完成后，删除对应的下载记录
     * @param path
     */
    public void delete(String path){
    	if(!wdb.isOpen())
    		wdb=getWritableDatabase();
        wdb.execSQL("delete from "+AppConfig.DB_DownLoad_TB+" where downpath=?", new Object[]{path});
        wdb.close();
    }
}